import time
from datetime import timedelta
import pytest
from unit_tools.handle_data.yaml_handler import clear_yaml
from unit_tools.other_utils.ding_rebot import send_dd_msg
from configs.setting import is_dd_msg


@pytest.fixture(scope="session", autouse=True)
def clear_extract():
    clear_yaml()


def format_duration(seconds):
    """
    将秒数转为时分秒格式
    :param seconds:传入的秒数
    :return:
    """
    return str(timedelta(seconds=seconds)).split('.')[0]


def pytest_terminal_summary(terminalreporter, exitstatus, config):
    """
    pytest预定义的钩子函数，用于在测试结束后自动收集测试结果
    :param terminalreporter:
    :param exitstatus:
    :param config:
    :return:
    """
    testcase_totle = terminalreporter._numcollected
    passed_num = len(terminalreporter.stats.get('passed', []))
    failed_num = len(terminalreporter.stats.get('failed', []))
    error_num = len(terminalreporter.stats.get('error', []))
    skip_num = len(terminalreporter.stats.get('skipped', []))
    duration = round(time.time() - terminalreporter._sessionstarttime, 2)
    formatted_duration = format_duration(duration)
    # 统计通过率、失败率、错误率
    pass_rate = f"{((passed_num + skip_num) / testcase_totle) * 100:.0f}%" if testcase_totle > 0 else "N/A"
    failed_rate = f"{(failed_num / testcase_totle) * 100:.0f}%" if testcase_totle > 0 else "N/A"
    error_rate = f"{(error_num / testcase_totle) * 100:.0f}%" if testcase_totle > 0 else "N/A"

    summary = f"""
    接口自动化测试结果，通知如下，具体执行结果：
    测试用例总数：{testcase_totle}
    用例通过数：{passed_num}  
    通过率：{pass_rate}
    用例失败数：{failed_num}  
    失败率：{failed_rate}
    用例错误数：{error_num}  
    错误率：{error_rate}
    跳过执行数：{skip_num}
    执行总时长：{duration} ({formatted_duration})
    """
    print(summary)
    if is_dd_msg:
        send_dd_msg(summary)

